package com.brsya.movie.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.brsya.base.base.BaseLayoutFragment;
import com.brsya.base.recycler.BaseAdapter;
import com.brsya.base.recycler.BaseViewHolder;
import com.brsya.base.util.GlideUtil;
import com.brsya.base.util.LoggerUtil;
import com.brsya.base.util.StringUtil;
import com.brsya.base.util.UiUtil;
import com.brsya.movie.R;
import com.bytedance.novel.pangolin.NovelSDK;
import com.bytedance.novel.pangolin.data.BookshelfBookInfo;

import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function2;

/**
 * Created by Brsya
 * CreateDate: 2022/8/2  8:54
 * Description:
 * 书架
 */
public class BookListFragment extends BaseLayoutFragment {
    private RelativeLayout rlTopTitle;
    private TextView tlMovieTitle;
    private LinearLayout llTitleBackBox;
    private View vFindSearchBox;
    private RecyclerView rlBookListBox;


    private int pageNumber = 1;
    private boolean isNextPage = false;

    private BaseAdapter<BookshelfBookInfo> adapter;

    private View.OnClickListener onBackClickListener;

    private Handler handler;

    private NovelSDK novelSDK;

    public static BookListFragment newInstance() {

        Bundle args = new Bundle();

        BookListFragment fragment = new BookListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        setContentViewId(R.layout.fragment_book_list);

        rlTopTitle = findViewById(R.id.rl_top_title);
        tlMovieTitle = findViewById(R.id.tl_movie_title);
        llTitleBackBox = findViewById(R.id.ll_title_back_box);
        vFindSearchBox = findViewById(R.id.v_find_search_box);
        rlBookListBox = findViewById(R.id.rl_book_list_box);
    }

    @Override
    protected void initData() {
        novelSDK = NovelSDK.INSTANCE;

        UiUtil.setStatusPadding(getContext(), rlTopTitle);

        llTitleBackBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onBackClickListener != null) {
                    onBackClickListener.onClick(view);
                }
            }
        });

        rlBookListBox.setLayoutManager(new LinearLayoutManager(getContext()));

        rlBookListBox.setAdapter(adapter = new BaseAdapter<BookshelfBookInfo>() {

            @Override
            public BaseViewHolder onCreate(ViewGroup parent, int viewType) {
                View rootView = LayoutInflater.from(getContext()).inflate(R.layout.item_book_list, parent, false);
                return new BaseViewHolder(rootView);
            }

            @Override
            public void onBind(BaseViewHolder viewHolder, int RealPosition, BookshelfBookInfo data) {

                ImageView ivBookImg = viewHolder.findViewById(R.id.iv_book_img);
                TextView tvBookTitle = viewHolder.findViewById(R.id.tv_book_title);
                TextView tvBookAbstract = viewHolder.findViewById(R.id.tv_book_abstract);
                TextView tvBookPlayTime = viewHolder.findViewById(R.id.tv_book_play_time);
                TextView tvBookPlayProgress = viewHolder.findViewById(R.id.tv_book_play_progress);

                GlideUtil.loadRound(ivBookImg, data.getThumbUrl(), 6);

                tvBookTitle.setText(data.getBookName());
                tvBookAbstract.setText(data.getAbstract());
                if ("1".equals(data.getCreationStatus())) {
                    tvBookPlayTime.setText(String.format("%s/连载中", data.getAuthor()));
                } else {
                    tvBookPlayTime.setText(String.format("%s/已完结", data.getAuthor()));
                }

                String date = StringUtil.generateDataOrTime(data.getLastOperateTime() * 1000L, "yyyy-MM-dd");
                tvBookPlayProgress.setText(String.format("最近阅读时间：%s", date));
            }
        });

        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener<BookshelfBookInfo>() {
            @Override
            public void onItemClick(int position, BookshelfBookInfo data) {
                //                Intent intent = new Intent(getActivity(), WebPageActivity.class);
                //                intent.putExtra(Contents.INTENT_H5_URL, data.getReadUrl());
                //                startActivity(intent);
                novelSDK.openNovelReaderByUrl(getContext(), data.getReadUrl());

            }
        });

        rlBookListBox.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (UiUtil.isSlideToBottom(recyclerView) && adapter != null && adapter.getDataList().size() > 0) {
                    loadBookList(false);
                }
            }
        });
        handler = new Handler(Looper.getMainLooper());
        loadBookList(true);

    }


    @Override
    public void onResume() {
        super.onResume();
        loadBookList(true);
    }

    private void loadBookList(boolean isFirst) {
        if (isFirst) {
            pageNumber = 1;
        } else {
            if (!isNextPage) {
                return;
            }
        }

        LoggerUtil.e("获取小说第几页：" + pageNumber);
        novelSDK.getBookshelf(pageNumber, new Function2<List<BookshelfBookInfo>, Boolean, Unit>() {
            @Override
            public Unit invoke(List<BookshelfBookInfo> bookshelfBookInfos, Boolean aBoolean) {
                LoggerUtil.e("获取小说成功：" + JSON.toJSONString(bookshelfBookInfos));
                isNextPage = aBoolean;
                if (bookshelfBookInfos.size() == 0) {
                    return null;
                }
                if (pageNumber == 1) {
                    adapter.setDataList(bookshelfBookInfos);
                } else {
                    adapter.addData(bookshelfBookInfos);
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                });
                if (aBoolean) {
                    pageNumber++;
                }
                return null;
            }
        });
    }

    public void setOnBackClickListener(View.OnClickListener onBackClickListener) {
        this.onBackClickListener = onBackClickListener;
    }
}
